const http = require('http');
const fs = require('fs');
const env = process.argv[2] || 'prod';

const directoryMap = {
  en: 'en_US',
  ja: 'ja_JP',
  zh_tw: 'zh_TW'
};

const getNative = language => new Promise((resolve, reject) => {
  console.log(`⌛️ Transforming the ${language}...`);
  const request = http.request({
    hostname: `${env === 'prod' ? 'console' : env}.huilianyi.com`,
    port: 80,
    path: `/multilanguage/web_${env}_${language}.json`,
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
    }
  }, res => {
    let content = '';
    res.setEncoding('utf8');
    res.on('data', data => {
      content += data;
    });
    res.on('end', () => {
      console.log(`👌️ Getting ${language} data success! `);
      let directoryName = directoryMap[language];
      console.log(`Writing ${language} to native... `);
      fs.writeFile(
        `./src/static/i18n/${directoryName}/${language === 'zh_tw' ? 'common' : 'index'}.json`,
        content,
        writeError => {
          if (writeError) {
            reject(writeError);
          } else {
            let jsContent = `import common from 'static/i18n/${directoryName}/common.json'${language === 'zh_tw' ? '' : `
import menu from 'static/i18n/${directoryName}/menu.json'
import index from 'static/i18n/${directoryName}/index.json'`}

const i18nList = [
  common${language === 'zh_tw' ? ',' : `,
  menu,
  index`}
];

let result = {};

i18nList.map(i18n => {
  result = Object.assign(result, i18n)
});

export default result;
`;
            fs.writeFile(`./src/share/i18n/${directoryMap[language]}.js`, jsContent, jsWriteError => {
              if (jsWriteError) {
                reject(jsWriteError);
              } else {
                resolve(language);
              }
            })
          }
        });
    })
  });
  request.on('error', e => {
    reject(e);
  });
  request.end();
});

const runPromiseByStep = list => {
  const [language, ...other] = list;
  getNative(language).then(() => {
    console.log(`👌️️ Writing ${language} success! `);
    console.log('');
    if(list.length > 1) {
      runPromiseByStep(other);
    } else {
      console.log('Finish')
    }
  }).catch(e => {
    console.error(e);
  })
};

runPromiseByStep(['zh_tw', 'en', 'ja']);

